<template>
  <a-modal
    v-model:open="modalVisible"
    title="态势对象关系维护"
    width="900px"
    :footer="null"
    @cancel="handleCancel"
  >
    <a-tabs v-model:activeKey="activeTab">
      <!-- 关系列表 -->
      <a-tab-pane key="list" tab="关系列表">
        <div class="action-bar">
          <a-space>
            <a-button type="primary" @click="handleCreate">
              <template #icon><PlusOutlined /></template>
              新建关系
            </a-button>
            <a-button @click="fetchRelationships">
              <template #icon><ReloadOutlined /></template>
              刷新
            </a-button>
          </a-space>
        </div>

        <a-table
          :dataSource="relationships"
          :columns="columns"
          :pagination="pagination"
          :loading="loading"
          @change="handleTableChange"
          rowKey="id"
          size="small"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'source'">
              {{ record.source_object_name }} ({{ record.source_object_code }})
            </template>

            <template v-else-if="column.key === 'relationship_type'">
              {{ getRelationshipTypeLabel(record.relationship_type) }}
            </template>

            <template v-else-if="column.key === 'target'">
              {{ record.target_object_name }} ({{ record.target_object_code }})
            </template>

            <template v-else-if="column.key === 'action'">
              <a-space>
                <a-button size="small" @click="handleViewTree(record.source_object_id)">查看关系树</a-button>
                <a-button size="small" @click="handleEdit(record)">编辑</a-button>
                <a-popconfirm
                  title="确认删除该关系吗?"
                  ok-text="确认"
                  cancel-text="取消"
                  @confirm="handleDelete(record.id)"
                >
                  <a-button size="small" danger>删除</a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
        </a-table>
      </a-tab-pane>

      <!-- 关系树 -->
      <a-tab-pane key="tree" tab="关系树">
        <div class="tree-controls">
          <a-space>
            <a-select
              v-model:value="treeRootId"
              placeholder="选择根对象"
              style="width: 300px"
              show-search
              :filter-option="filterOption"
              @change="handleTreeRootChange"
            >
              <a-select-option v-for="obj in allObjects" :key="obj.id" :value="obj.id">
                {{ obj.name }} ({{ obj.code }})
              </a-select-option>
            </a-select>

            <a-select v-model:value="maxLevel" style="width: 120px" @change="loadRelationshipTree">
              <a-select-option :value="1">1级关系</a-select-option>
              <a-select-option :value="2">2级关系</a-select-option>
              <a-select-option :value="3">3级关系</a-select-option>
              <a-select-option :value="4">4级关系</a-select-option>
              <a-select-option :value="5">5级关系</a-select-option>
            </a-select>

            <a-button type="primary" @click="loadRelationshipTree" :loading="treeLoading">
              <template #icon><ReloadOutlined /></template>
              加载关系树
            </a-button>
          </a-space>
        </div>

        <div class="tree-container">
          <a-tree
            v-if="treeData.length > 0"
            :tree-data="treeData"
            :default-expand-all="true"
            :show-line="true"
          >
            <template #title="{ title, relationship_type }">
              <span>
                {{ title }}
                <a-tag v-if="relationship_type" color="blue" size="small">{{ getRelationshipTypeLabel(relationship_type) }}</a-tag>
              </span>
            </template>
          </a-tree>
          <a-empty v-else description="请选择根对象并加载关系树" />
        </div>
      </a-tab-pane>
    </a-tabs>

    <!-- 新建/编辑关系弹窗 -->
    <a-modal
      v-model:visible="showFormModal"
      :title="editingRelationship ? '编辑关系' : '新建关系'"
      @ok="handleFormSubmit"
      @cancel="showFormModal = false"
    >
      <a-form :model="formData" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="源对象" required>
          <a-select
            v-model:value="formData.source_object_id"
            placeholder="请选择源对象"
            show-search
            :filter-option="filterOption"
            :disabled="!!editingRelationship"
          >
            <a-select-option v-for="obj in allObjects" :key="obj.id" :value="obj.id">
              {{ obj.name }} ({{ obj.code }})
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="目标对象" required>
          <a-select
            v-model:value="formData.target_object_id"
            placeholder="请选择目标对象"
            show-search
            :filter-option="filterOption"
            :disabled="!!editingRelationship"
          >
            <a-select-option v-for="obj in allObjects" :key="obj.id" :value="obj.id">
              {{ obj.name }} ({{ obj.code }})
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="关系类型" required>
          <a-select
            v-model:value="formData.relationship_type"
            placeholder="请选择关系类型"
            show-search
            :filter-option="filterOption"
            :disabled="!!editingRelationship"
          >
            <a-select-option v-for="type in relationshipTypes" :key="type.value" :value="type.value">
              {{ type.label }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="关系描述">
          <a-textarea v-model:value="formData.description" :rows="3" placeholder="请输入关系描述" />
        </a-form-item>

        <a-alert type="info" show-icon style="margin-top: 8px">
          <template #message>
            关系层级说明
          </template>
          <template #description>
            系统会根据源对象在关系链中的位置自动计算层级：
            <ul style="margin: 8px 0 0 20px; padding: 0">
              <li>如果源对象是根节点（没有其他对象指向它），创建的关系为1级</li>
              <li>如果源对象已是某个关系的目标，新关系层级会自动递增</li>
              <li>系统最多支持5级关系链</li>
            </ul>
          </template>
        </a-alert>
      </a-form>
    </a-modal>
  </a-modal>
</template>

<script setup>
import { ref, reactive, watch, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined, ReloadOutlined } from '@ant-design/icons-vue'
import {
  getRelationships,
  createRelationship,
  updateRelationship,
  deleteRelationship,
  getRelationshipTree,
  validateCycle,
  getSituationObjects,
  getRelationshipTypes
} from '@/apis'

const props = defineProps({
  open: Boolean
})

const emit = defineEmits(['update:open'])

const visible = ref(false)

// 计算属性处理 v-model:open
const modalVisible = computed({
  get: () => props.open,
  set: (val) => emit('update:open', val)
})
const activeTab = ref('list')
const loading = ref(false)
const relationships = ref([])
const allObjects = ref([])
const relationshipTypes = ref([])

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

const columns = [
  { title: '源对象', key: 'source', width: 200 },
  { title: '关系类型', key: 'relationship_type', width: 120 },
  { title: '目标对象', key: 'target', width: 200 },
  { title: '层级', dataIndex: 'relationship_level', key: 'relationship_level', width: 80 },
  { title: '描述', dataIndex: 'description', key: 'description', ellipsis: true },
  { title: '操作', key: 'action', width: 220, fixed: 'right' }
]

// 表单相关
const showFormModal = ref(false)
const editingRelationship = ref(null)
const formData = reactive({
  source_object_id: undefined,
  target_object_id: undefined,
  relationship_type: '',
  description: ''
})

// 关系树相关
const treeRootId = ref(undefined)
const maxLevel = ref(5)
const treeLoading = ref(false)
const treeData = ref([])

watch(() => props.open, (val) => {
  visible.value = val
  if (val) {
    loadAllObjects()
    loadRelationshipTypes()
    fetchRelationships()
  }
})

watch(visible, (val) => {
  emit('update:open', val)
})

// 注意：不在 onMounted 中预加载数据，只在弹窗打开时加载
// 这样可以避免重复请求，并确保数据是最新的

// 加载所有对象
async function loadAllObjects() {
  try {
    console.log('[关系维护] 开始加载态势对象列表...')

    // 由于后端限制 page_size 最大为 100，需要分页加载所有数据
    let allItems = []
    let page = 1
    const pageSize = 100
    let hasMore = true

    while (hasMore) {
      const response = await getSituationObjects({ page, page_size: pageSize })
      allItems = allItems.concat(response.items || [])

      // 检查是否还有更多数据
      if (response.items.length < pageSize || allItems.length >= response.total) {
        hasMore = false
      } else {
        page++
      }
    }

    allObjects.value = allItems
    console.log('[关系维护] 加载成功，对象总数:', allItems.length)
  } catch (error) {
    console.error('[关系维护] 加载对象列表失败:', error)

    let errorMsg = '未知错误'
    if (error instanceof Error) {
      errorMsg = error.message
    } else if (typeof error === 'string') {
      errorMsg = error
    } else if (error && error.toString) {
      errorMsg = error.toString()
    }

    message.error('加载对象列表失败: ' + errorMsg)
  }
}

// 获取关系列表
async function fetchRelationships() {
  loading.value = true
  try {
    const response = await getRelationships({
      page: pagination.current,
      page_size: pagination.pageSize
    })
    relationships.value = response.items
    pagination.total = response.total
  } catch (error) {
    message.error('获取关系列表失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 表格变化
function handleTableChange(pag) {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchRelationships()
}

// 新建关系
function handleCreate() {
  editingRelationship.value = null
  Object.assign(formData, {
    source_object_id: undefined,
    target_object_id: undefined,
    relationship_type: '',
    description: ''
  })
  showFormModal.value = true
}

// 编辑关系
function handleEdit(record) {
  editingRelationship.value = record
  Object.assign(formData, {
    source_object_id: record.source_object_id,
    target_object_id: record.target_object_id,
    relationship_type: record.relationship_type,
    description: record.description
  })
  showFormModal.value = true
}

// 提交表单
async function handleFormSubmit() {
  if (!formData.source_object_id || !formData.target_object_id || !formData.relationship_type) {
    message.error('请填写必填字段')
    return
  }

  // 检查源对象和目标对象不能相同
  if (formData.source_object_id === formData.target_object_id) {
    message.error('源对象和目标对象不能相同')
    return
  }

  // 检查循环依赖
  if (!editingRelationship.value) {
    try {
      const cycleCheck = await validateCycle({
        source_object_id: formData.source_object_id,
        target_object_id: formData.target_object_id,
        relationship_type: formData.relationship_type
      })

      if (cycleCheck.has_cycle) {
        message.error('创建关系会导致循环依赖: ' + cycleCheck.message)
        return
      }
    } catch (error) {
      message.error('循环检测失败: ' + error.message)
      return
    }
  }

  try {
    if (editingRelationship.value) {
      await updateRelationship(editingRelationship.value.id, {
        relationship_type: formData.relationship_type,
        description: formData.description
      })
      message.success('更新成功')
    } else {
      await createRelationship(formData)
      message.success('创建成功')
    }

    showFormModal.value = false
    fetchRelationships()
  } catch (error) {
    message.error('操作失败: ' + error.message)
  }
}

// 删除关系
async function handleDelete(id) {
  try {
    await deleteRelationship(id)
    message.success('删除成功')
    fetchRelationships()
  } catch (error) {
    message.error('删除失败: ' + error.message)
  }
}

// 查看关系树
function handleViewTree(objectId) {
  activeTab.value = 'tree'
  treeRootId.value = objectId
  loadRelationshipTree()
}

// 关系树根节点变化
function handleTreeRootChange() {
  if (treeRootId.value) {
    loadRelationshipTree()
  }
}

// 加载关系树
async function loadRelationshipTree() {
  if (!treeRootId.value) {
    message.warning('请先选择根对象')
    return
  }

  treeLoading.value = true
  try {
    const response = await getRelationshipTree(treeRootId.value, maxLevel.value)
    treeData.value = [convertToTreeData(response)]
  } catch (error) {
    message.error('加载关系树失败: ' + error.message)
  } finally {
    treeLoading.value = false
  }
}

// 转换为 Ant Design 树组件数据格式
function convertToTreeData(node) {
  return {
    key: node.object_id,
    title: `${node.object_name} (${node.object_code || '-'})`,
    relationship_type: node.relationship_type,
    children: node.children.map(child => convertToTreeData(child))
  }
}

// 加载关系类型
async function loadRelationshipTypes() {
  try {
    console.log('[关系维护] 开始加载关系类型列表...')
    const response = await getRelationshipTypes()
    relationshipTypes.value = response.categories || []
    console.log('[关系维护] 关系类型加载成功，总数:', relationshipTypes.value.length)
  } catch (error) {
    console.error('[关系维护] 加载关系类型失败:', error)
    message.error('加载关系类型失败: ' + error.message)
  }
}

// 获取关系类型中文标签
function getRelationshipTypeLabel(relationshipType) {
  const typeItem = relationshipTypes.value.find(item => item.value === relationshipType)
  return typeItem ? typeItem.label : relationshipType
}

// 搜索过滤
function filterOption(input, option) {
  return option.children[0].toLowerCase().indexOf(input.toLowerCase()) >= 0
}

// 关闭弹窗
function handleCancel() {
  visible.value = false
}
</script>

<style scoped>
.action-bar {
  margin-bottom: 16px;
}

.tree-controls {
  margin-bottom: 16px;
  padding: 16px;
  background: #f5f5f5;
  border-radius: 4px;
}

.tree-container {
  padding: 16px;
  min-height: 400px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}
</style>
